package com.haidechizi.sort;

import java.util.Arrays;

/**
 * @author: wangdejun
 * @create: 2020-03-14 14:42
 **/
public class HeapSort {

    public static void main(String[] args) {
        int[] arr = new int[]{8, 3, 5, 0, 1, 4, 6, 7};
        heapSort(arr);
        System.out.println(Arrays.toString(arr));
    }

    public static void heapSort(int[] arr) {
        int start = (arr.length - 1) / 2;
        for (int i = start; i >= 0; i--) {
            maxHeap(arr, arr.length, i);
        }
        for (int i = arr.length - 1; i > 0; i--) {
            int temp = arr[0];
            arr[0] = arr[i];
            arr[i] = temp;
            maxHeap(arr, i, 0);
        }

    }


    // 大顶堆
    public static void maxHeap(int[] arr, int size, int index) {
        int max = index;
        int left = 2 * index + 1;
        if (left < size && arr[left] > arr[max]) {
            max = left;
        }
        int right = 2 * index + 2;
        if (right < size && arr[right] > arr[max]) {
            max = right;
        }

        if (index != max) {
            // 交换顺序
            int temp = arr[max];
            arr[max] = arr[index];
            arr[index] = temp;
            maxHeap(arr, size, max);
        }

    }
}
